using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToDoListWeb.Models;

namespace ToDoListWeb.Service
{
    public class TypeService
    {
        private ToDoListWebContext _ctx = new ToDoListWebContext();

        /// <summary>
        /// 通过typeId获取Type对象
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public Models.Type GetType(int typeId)
        {
            return _ctx.Type.Include("Inventory").SingleOrDefault(t=>t.TypeId==typeId);
        }
        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="typeId"></param>
        public void DeleteType(int typeId)
        {
            var type = _ctx.Type.SingleOrDefault(t=>t.TypeId==typeId);
            _ctx.Type.Remove(type);
            _ctx.Inventory.RemoveRange(_ctx.Inventory.Where(i=>i.TypeId==typeId).ToList());
            _ctx.Matter.RemoveRange(_ctx.Matter.Where(m=>m.TypeId==typeId).ToList());
            _ctx.SaveChanges();
        }
        /// <summary>
        /// 编辑类型内容
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="typeName"></param>
        public void ChangeTypeName(int typeId,string typeName)
        {
            _ctx.Type.Single(t => t.TypeId == typeId).TypeName = typeName;
            _ctx.SaveChanges();
        }
        /// <summary>
        /// 创建新类型
        /// </summary>
        /// <param name="user"></param>
        /// <param name="typeName"></param>
        public void CreateType(UserModel user,string typeName)
        {
            Models.Type type = new Models.Type()
            {
                UserId=user.UserId,
                TypeName=typeName
            };
            _ctx.Type.Add(type);
            _ctx.SaveChanges();
        }
    }
}
